import os
import subprocess

import mimetypes

#from assets.models import *

from damn import FileReference, AssetReference
from PIL import Image

  
def CountColors(img):
  def GetColor(x):
    return ['R', 'G', 'B'][x.index(max(*x))]
  def Parse(data):
    return map(lambda x: GetColor(x), data)
    
  im = img.resize((128, 128))
  im = im.convert("RGB")
  data = Parse(im.getdata())
  
  import zlib
  d = list(im.getdata())
  length = len(zlib.compress(str(d)))
  
  return data.count('R'), data.count('G'), data.count('B'), length

from damn.analyzer import BaseAnalyzer
class ImageAnalyzer(BaseAnalyzer):
  handled_types = ["image/jpeg", "image/png", "image/tga", "image/gif", "image/tiff", "image/x-photoshop"]

  def analyze(self, anURI):
    f = FileReference(anURI)
    a = AssetReference(os.path.basename(anURI), mimetypes.guess_type(anURI, False)[0], f)
    
    try:  
      im = Image.open(anURI)
      a.AddMetaData('resolution-width', im.size[0])
      a.AddMetaData('resolution-height', im.size[1])
      a.AddMetaData('PIL-format', im.format)
      a.AddMetaData('PIL-mode', im.mode)
      r,g,b, l = CountColors(im)
      a.AddMetaData('avg-color-count-red', r)
      a.AddMetaData('avg-color-count-green', g)
      a.AddMetaData('avg-color-count-blue', b)
      
      a.AddMetaData('avg-compress-length', l)
    except IOError:
      print("E: ImageAnalyzer: cannot open", anURI)

    return f
